package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.model.dtos.ResponseResult;

import com.heima.model.enums.AppHttpCodeEnum;
import com.heima.model.user.ApUser;
import com.heima.model.user.LoginDto;
import com.heima.user.mapper.UserLoginMapper;
import com.heima.user.service.IUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl implements IUserLoginService {
    @Autowired
    private UserLoginMapper userLoginMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone,dto.getPhone());
        ApUser apUser = userLoginMapper.selectOne(wrapper);
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String password = apUser.getPassword();
        String salt = apUser.getSalt();
        //通过dot中的密码加上盐对比密码是否正确
        String md5 = DigestUtils.md5DigestAsHex((dto.getPassword()+salt).getBytes());
        if (!password.equals(md5)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        apUser.setPhone(" ");
        apUser.setPassword(" ");
        //获取token

        String token = AppJwtUtil.getToken(apUser.getId().longValue());
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",apUser);

        return ResponseResult.okResult(map);
    }
}
